// kit-web 简单的测试web服务，可以发布静态资源，或设置访问睡眠时间
// 可以根据配置文件返回请求
// 如果返回文件中有UUID字符串，会用shortuuid替换
package main

import (
	"flag"
	"fmt"
	"time"

	"gitee.com/xuender/kits/webs"
	"gitee.com/xuender/oils/base"
	"gitee.com/xuender/oils/logs"
	"github.com/kataras/iris/v12"
	"github.com/xuender/oil/str"
)

const port = 8765

func main() {
	var (
		cliPort     int
		cliDir      string
		cliSleep    int
		cliDebug    bool
		cliCompress bool
		cliConfig   string
	)

	flag.IntVar(&cliPort, "p", port, "Http port number.")
	flag.StringVar(&cliDir, "w", ".", "Web static dir.")
	flag.IntVar(&cliSleep, "s", 0, "Sleep millisecond.")
	flag.BoolVar(&cliDebug, "d", false, "Debug mode.")
	flag.BoolVar(&cliCompress, "g", false, "Gzip compress.")
	flag.Parse()

	if flag.NArg() > 0 {
		cliConfig = flag.Arg(0)
	}

	app := iris.New()

	logs.Debugw("app", "port", cliPort, "dir", cliDir, "sleep", cliSleep, "compress", cliCompress)
	app.Use(func(ctx iris.Context) {
		if cliDebug {
			start := time.Now()
			defer func() {
				r := ctx.Request()
				use := str.Time(time.Since(start).Nanoseconds())
				app.Logger().Debugf("%s %d %s %s", r.Method, ctx.GetStatusCode(), use, r.URL.Path)
			}()
		}

		if cliSleep > 0 {
			time.Sleep(time.Duration(cliSleep) * time.Millisecond)
		}
		ctx.Next()
	})
	app.HandleDir("/", cliDir, iris.DirOptions{IndexName: "/index.html", Gzip: cliCompress})

	if cliConfig != "" {
		handles := base.Panic1(webs.Load(cliConfig))
		app.Logger().Debugf("Load config %s", cliConfig)

		for _, h := range handles {
			app.Handle(h.Method, h.Path, h.Handler)
			app.Logger().Infof("Add hand %s: %s %s", h.Method, h.Path, h.File)
		}
	}

	count := 0

	app.Get("/count", func(ctx iris.Context) {
		count++

		_, _ = ctx.JSON(count)
	})

	base.Panic(app.Listen(fmt.Sprintf(":%d", cliPort)))
}
